package com.media.appmedia.appupdata;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.media.appmedia.R;
import com.media.appmedia.base.BaseApplication;
import com.media.appmedia.network.ProtocolService;
import com.media.appmedia.util.MethodUtils;
import com.media.appmedia.util.PhoneInfoUtils;
import com.media.appmedia.util.ToastUtils;

/**
 * 新版本更新信息
 * 
 * @author Rose
 * @since 2013_12_12
 * 
 */
public class NewVersion {
	private String tag = "Config";
	private int newVersionCode;
	private String newVersionName;
	private Context context;
	private String downloadPath;
	private String appVersion;
	private String newApkName;
	private ProgressDialog progress;
	private File file;
	private int apkSize;
	private String appHint;
	// 是否强制更新
	private boolean flage = false;

	/**
	 * 构造函数
	 * 
	 * @param context上下文
	 * @param downloadPath下载地址
	 * @param appVersion应用程序版本信息文件
	 */
	public NewVersion(Context context, String downloadPath, String appHint) {
		this.context = context;
		this.downloadPath = downloadPath;
		this.appHint = appHint;
	}

	/**
	 * 检测更新
	 * 
	 * @throws Exception
	 */
	public void checkUpdateVersion() throws Exception {
		if (!isNetworkAvailable()) {
			Toast.makeText(context, "网络不可用！", Toast.LENGTH_SHORT).show();
			return;
		}
		// JSON版本信息下载
		ProtocolService.getViersion(PhoneInfoUtils.getIMEI(context),
				new RequestCallBack<String>() {
					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						System.out.println();
						if (getServerVersion(arg0.result)) {
							int x = CurrentVersion.getVersionCode(context);
							if (newVersionCode > x) {
								try {
									showUpdateDialog();
								} catch (Exception e) {
									e.printStackTrace();
								}
							} else if (MethodUtils.isEmpty(appHint)) {
								ToastUtils.show(context, "当前是最新版本");
							}
						} else {
							if (MethodUtils.isEmpty(appHint)) {
								ToastUtils.show(context, "当前是最新版本");
							}
						}
					}

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						ToastUtils.show(context,
								R.string.phone_verify_send_fail);
					}
				});
	}

	/**
	 * 获取新版本信息
	 * 
	 * @param newVersionJson
	 * @return
	 */
	private boolean getServerVersion(String newVersionJson) {

		try {
			JSONArray jsonArray = new JSONArray(newVersionJson);
			if (jsonArray.length() > 0) {
				JSONObject jsonObject = jsonArray.getJSONObject(0);
				newVersionCode = Integer.parseInt(jsonObject
						.getString("versionCode"));
				newVersionName = jsonObject.getString("app_name");
				newApkName = jsonObject.getString("apkname");
				apkSize = Integer.parseInt(jsonObject.getString("apksize"));
				flage = jsonObject.getString("force_update").equals("true");
				appVersion = jsonObject.getString("apkinfo");
			}
		} catch (JSONException e) {
			newVersionCode = -1;
			newVersionName = "";
			newApkName = "";
			return false;
		}

		return true;
	}

	/**
	 * 显示更新对话框
	 */
	private void showUpdateDialog() {
		StringBuilder sb = new StringBuilder();
		sb.append("当前版本：");
		sb.append(CurrentVersion.getVersinName(context));
		sb.append("\n");
		sb.append("发现新版本：");
		sb.append(newVersionName);
		sb.append("\n");
		sb.append("大小：");
		System.out.println(apkSize);
		sb.append(byteToMB(apkSize) + "M");
		sb.append("\n");
		sb.append(appVersion);
		sb.append("\n");
		sb.append("是否更新");
		Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("软件更新");
		builder.setMessage(sb);
		builder.setPositiveButton("确定", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				progress = new ProgressDialog(context);
				progress.setTitle("正在下载...");
				progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				progress.setIndeterminate(false);
				progress.setCancelable(false);
				progress.setProgress(0);
				progress.show();
				downloadApk(downloadPath + newApkName);
			}
		});
		builder.setNegativeButton("暂不更新", new OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				isUpdata();
			}
		});
		builder.setCancelable(false);
		builder.create().show();
	}

	/**
	 * 下载文件
	 */
	private void downloadApk(String apkPath) {
		AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
		asyncHttpClient.get(apkPath, new AsyncHttpResponseHandler() {

			@Override
			public void onFinish() {
				try {
					Thread.sleep(3000);
					showcomplelteDiloage();
				} catch (InterruptedException e) {
					progress.dismiss();
					e.printStackTrace();
				}
			}

			@SuppressLint("NewApi")
			@Override
			public void onProgress(int bytesWritten, int totalSize) {
				progress.setProgressNumberFormat("%1d k/%2d k");
				progress.setMax(byteToKB(totalSize));
				progress.setProgress(byteToKB(bytesWritten));
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				System.out.println(arg1);
				try {
					file = new File(Environment.getExternalStorageDirectory(),
							"sgfc88.apk");
					FileOutputStream fs = new FileOutputStream(file);
					fs.write(arg2, 0, arg2.length);
					fs.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}

		});

	}

	/**
	 * 下载完成对话框
	 */
	private void showcomplelteDiloage() {
		Builder builder = new AlertDialog.Builder(context);
		builder.setTitle("下载通知");
		builder.setMessage("下载完成是否安装？");
		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				installNewApk();
				progress.dismiss();
			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				isUpdata();
				progress.dismiss();
			}
		});
		builder.setCancelable(false);
		builder.create().show();
	}

	/**
	 * 安装文件
	 */
	private void installNewApk() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		context.startActivity(intent);
	}

	/**
	 * 字节转换为Mb
	 * 
	 * @param kb大小
	 * @return Mb大小
	 */
	private float byteToMB(int bt) {
		int mb = 1024;
		float f = (float) bt / mb;
		float temp = Math.round(f * 100);
		return temp / 100;

	}

	/**
	 * 字节转换为kb
	 * 
	 * @param 字节大小
	 * @return kb大小
	 */
	private int byteToKB(int bt) {
		return Math.round(bt / 1024);
	}

	/**
	 * 检测网络是否可用
	 * 
	 * @return 是否可用
	 */
	private boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		return (ni != null && ni.isAvailable());
	}

	/**
	 * 
	 * 方法说明：实现点击取消是否退出程序，当需要强制更新时 flage为true 此时点击取消则退出程序
	 * 
	 */
	private void isUpdata() {
		if (flage) {
			BaseApplication.getApplication().backAct();
		}
	}
}
